import React, { useState, useEffect } from 'react'
import { Table, Divider, Input, Button, Popconfirm} from 'antd';
import './index.less';
import { BasicLayout } from '@components/layout';
import createServerModal from './create_server_modal/index';
import ServerApi from '@request/server_manage';
import {apiTypes} from '../mock';

export interface ServerRecord {
  api_infos: APIInfos[],
  create_time: string,
  desc: string,
  id: number,
  name: string,
  type: string,
  update_time: string
}
interface APIInfos {
  id: number,
  name: string,
  weight: number
}
interface DataList {
  totalNum?: number,
  list?: ServerRecord[],
  current?: number
}
interface request {
  current_page_num?: number,
  name?: string,
  page_size?: number,
  type?: string
}
interface requestParams {
  currentPageNum?: number,
  curKeyword?: string
}

const pageSize = 20;
function ServerManage(props: any) {
  const [data, setData] = useState<DataList>({});
  const [keyword, setKeyword] = useState<string>('');
  const [pageNum, setPageNum] = useState(1);
  const [type, setType] = useState<string | undefined>(undefined);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    getList();
  }, []);
  const getList = (requests: requestParams = {}) => {
    const { currentPageNum, curKeyword } = requests;
    let params: request = {
      page_size: pageSize,
      current_page_num: currentPageNum || pageNum,
      name: keyword.trim()
    };
    if(curKeyword || curKeyword === '') params.name = curKeyword.trim();
    if (type) params.type = type;
    setLoading(true);
    ServerApi.getServerList({
      params: params
    })
      .then(res => {
        setData(() => {
          return {
            totalNum: res.count_num,
            list: res.data,
            current: res.current_page_num
          }
        })
      })
      .catch(err => {
        console.log('err: ', err);
      })
      .finally(() => {
        setLoading(false);
      })
  }
  const columns = [
    {
      dataIndex: 'name',
      title: '服务名称'
    },
    {
      dataIndex: 'type',
      title: '服务类型',
      render: (text: string) => {
        let info = apiTypes.find(item => item.key === text);
        return info?.name;
      }
    },
    {
      dataIndex: 'apiAmount',
      title: 'API数量',
      render: (_text: '', record: ServerRecord) => {
        return record.api_infos.length;
      }
    },
    {
      dataIndex: 'desc',
      title: '描述'
    },
    {
      dataIndex: 'create_time',
      title: '创建时间'
    },
    {
      dataIndex: '',
      title: '操作',
      render: (_text: string, record: ServerRecord) => {
        return <div>
          <a onClick={() => addSerVerModal('view', record)}>查看</a>
          <Divider type="vertical" />
          <a onClick={() => addSerVerModal('edit', record)}>编辑</a>
          <Divider type="vertical" />
          <Popconfirm
              title={`确定删除${record.name}吗？`}
              onConfirm={() => delServer(record)}
            >
              <a >删除</a>
            </Popconfirm>
        </div>
      }
    }
  ];
  const addSerVerModal = (type: string, record: ServerRecord | {} = {}) => {
    createServerModal({
      type,
      record,
      getList
    })
  }
  const delServer = async (record: ServerRecord) => {
    await ServerApi.delServerById({ query: { id: record.id } });
    getList({currentPageNum: 1});
  }
  const search = (value: string) => {
    setKeyword(value);
    getList({curKeyword: value});
  }
  const { totalNum, list } = data;
  return (
    <BasicLayout
      title='服务管理'
      className='server-manage'
      addButton={
        <Button type='primary' onClick={() => addSerVerModal('add', {})}>创建服务</Button>
      }
      extra={
        <>
          <Input.Search
            onChange={(e) => search(e.target.value)}
            value={keyword}
            onSearch={(value) => search(value)}
          />
        </>
      }
    >
      <Table
        columns={columns}
        dataSource={list}
        loading={loading}
        scroll={{y: `calc(100vh - 300px)`}}
        bordered
        pagination={{
          total: totalNum,
          pageSize: pageSize,
          showQuickJumper: true,
          showSizeChanger: false,
          showTotal: (total) => `总共${total}条`,
          current: pageNum,
          onChange: (page, pageSize) => {
            setPageNum(page);
            getList({ currentPageNum: page })
          }
        }}
      />
    </BasicLayout>
  )
}

export default ServerManage;